#include "Polygon.h"
#include "Triangle.h"

Polygon::Polygon() : Primitive()
{
}

Polygon::~Polygon()
{
}

void Polygon::addTriangle(Math::Triangle t){
    m_Triangles.push_back(t);
}

bool Polygon::intersects(Math::Ray &ray, float &distance, bool second){
    std::vector<Math::Triangle>::iterator it;
    float localDist = distance;
    bool intersected = false;
    for(it = m_Triangles.begin();it != m_Triangles.end();it++){
        if (it->intersects(ray,localDist)){
			if (localDist<distance){
                distance = localDist;
                intersected = true;
            }
        }
    }
    return intersected;
}

int Polygon::intersects(Math::Plane &plane, float &distance){
	return INTERSECTS;
}

void Polygon::calculatesConstants(Math::Vector &pos)
{
}

void Polygon::getIntersectionParams(Math::Ray &ray,const float t, Math::Vector* normal, Math::Vector* uv){
    std::vector<Math::Triangle>::iterator it;
    float localDist = t;
    bool intersected = false;
    Math::Triangle* nearest = NULL;
    for(it = m_Triangles.begin();it != m_Triangles.end();it++){
        if (it->intersects(ray,localDist)){
			if (localDist<=t){//normally should only find one, ==
                nearest = &(*it);
                intersected = true;
            }
        }
    }
    if (intersected){
        nearest->getIntersectionParams(ray,t,normal,uv);
    }
}

void Polygon::smooth(){
    std::vector<Math::Triangle>::iterator it,it2;
    int i=0,j=0;
    for(it = m_Triangles.begin();it != m_Triangles.end();it++){
        it2 = it; it2++;
        j=i;
        for (;it2!=m_Triangles.end();it2++){
            it->mixNormals(*it2);
            j++;
        }
        it->recalcNormals();
        i++;
    }
}
